package com.libgdxbar.pvzlikegame.screens.gamescreens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.utils.ScreenUtils;
import com.libgdxbar.pvzlikegame.screens.GameScreenAdapter;

/*
当前仅android可以捕获, desktop也不需要
 */
public class ExceptionCaptorTestScreen extends GameScreenAdapter {
	private Stage stage;
	private Skin skin;
	public static Runnable mainExceptionTest;

	@Override
	public void create() {
		skin = new Skin(Gdx.files.internal("ui_skins/shade/skin/uiskin.json"));
		skin.getFont("font-button").getData().setScale(2.5f);

		stage = new Stage(getViewport());
		getImp().addProcessor(stage);
		newExceptionTextBtn("Exception1", 1, stage, () -> {
			throw new RuntimeException("测试异常1-GL线程异常");
		});
		newExceptionTextBtn("Exception2", 2, stage, () -> {
			new Thread(()->{
				throw new RuntimeException("测试异常2-子线程异常");
			}).start();
		});
		newExceptionTextBtn("Exception3", 3, stage, () -> {
				if(mainExceptionTest != null) mainExceptionTest.run();
		});
	}

	private void newExceptionTextBtn(String btnText, float vertiOffset, Stage stage, final Runnable runnable) {
		TextButton btn = new TextButton(btnText, skin);
		float margin = 15;
		btn.setPosition(getViewCenter().x - btn.getWidth() / 2, getViewCenter().y*2 - btn.getHeight() / 2 - vertiOffset * (btn.getHeight()+margin));
		btn.addListener(new InputListener() {
			public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
				return true;
			}

			public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
				if (runnable != null) runnable.run();
			}
		});
		stage.addActor(btn);
	}

	@Override
	public void render(float delta) {
		ScreenUtils.clear(0, 0.1f, 0.5f, 1);

		stage.act(delta);
		stage.draw();

	}
}
